import 'package:abc/model/post_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get_utils/get_utils.dart';


const Color _textColor = Colors.white;
class PostCell extends StatelessWidget {
  final Post post;

  const PostCell({super.key, required this.post});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 20, bottom: 12, left: 10, right: 10),
      margin: const EdgeInsets.only(bottom: 8),

      decoration: BoxDecoration(
        color: Color(0x33959595),
        borderRadius: BorderRadius.circular(32),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(), // 顶部：头像、用户名、时间、关注按钮
          const SizedBox(height: 10),
          _buildImageGrid(), // 核心难点：动态图片区域
          const SizedBox(height: 10),
          _buildContent(), // 内容：标题、文本摘要
          const SizedBox(height: 10),
          _buildTags(),
          const SizedBox(height: 10),
          _buildFooter(), // 底部：点赞、评论、分享
        ],
      ),
    );
  }

  // --- 头部布局 ---
  Widget _buildHeader() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        // 1. 头像
        CircleAvatar(radius: 24, backgroundImage: NetworkImage(post.avatarUrl)),
        const SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 2. 用户名和等级 (假设等级是小图标)
              Row(
                children: [
                  Text(
                    post.username,
                    style: const TextStyle(
                      color: _textColor,
                      fontWeight: FontWeight.w600,
                      fontSize: 15,
                    ),
                  ),
                  const SizedBox(width: 2),
                  Image.asset('assets/images/vip.png', width: 30, height: 15),
                ],
              ),
              // 3. 时间
              Text(
                post.time,
                style: const TextStyle(
                  color: Colors.white60,
                  fontSize: 11,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ),
        // 4. 关注/已关注按钮
        Container(
          width: 55,
          padding: const EdgeInsets.symmetric(vertical: 5),
          decoration: BoxDecoration(
            gradient: post.isFollowed
                ? LinearGradient(
                    colors: [Color(0xFFDADADA), Color(0xFFDADADA)],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  )
                : LinearGradient(
                    colors: [Color(0xFFA877F4), Color(0xFF5650D6)],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  ),
            borderRadius: BorderRadius.circular(15),
          ),
          child: Center(
            child: Text(
              post.isFollowed ? '已关注' : '关注',
              style: TextStyle(
                color: post.isFollowed ? Color(0xFF333333) : _textColor,
                fontSize: 13,
              ),
            ),
          ),
        ),
      ],
    );
  }

  // --- 内容布局 ---
  Widget _buildContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          post.title,
          style: const TextStyle(
            color: _textColor,
            fontSize: 15,
            fontWeight: FontWeight.w600,
          ),
        ),
        post.content.isEmpty?Container(): SizedBox(height: 10),
        post.content.isEmpty?Container(): Text(
          post.content,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(
            color: Colors.white60,
            fontSize: 15,
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  Widget _buildImageGrid() {
    final imageCount = post.imageUrls.length;
    if (imageCount == 0) {
      return const SizedBox.shrink();
    }

    // 1. 单张大图
    if (imageCount == 1) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.network(
          post.imageUrls[0],
          fit: BoxFit.cover,
          width: double.infinity,
          height: 243, // 固定高度
        ),
      );
    }

    // 2. 多图网格 (最多显示 3 张，多余的显示计数)
    return LayoutBuilder(
      builder: (context, constraints) {
        // 计算每个小图的宽度（最多三张图并排，间距为5）
        final itemWidth = (constraints.maxWidth - 10) / 3;

        // 确定要显示的图片列表 (最多取前 3 张)
        final displayUrls = post.imageUrls.take(3).toList();
        final isOverflow = imageCount > 3; // 是否溢出

        return Wrap(
          spacing: 5.0, // 水平间距
          runSpacing: 5.0, // 垂直间距
          children: List.generate(displayUrls.length, (index) {
            // 检查当前是否是第三张图且图片数量超过3张
            final isThirdAndOverflow = isOverflow && index == 2;

            Widget imageWidget = ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.network(
                displayUrls[index],
                width: itemWidth,
                height: 140, // 保持正方形
                fit: BoxFit.cover,
              ),
            );

            if (isThirdAndOverflow) {
              return Stack(
                alignment: Alignment.center,
                children: [
                  // 基础图片
                  imageWidget,

                  // 计数文本
                  Positioned(
                    bottom: 5,
                    right: 5,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 1,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.black54,
                        borderRadius: BorderRadius.circular(2),
                      ),
                      child: Text(
                        '${imageCount}图',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }

            return imageWidget;
          }),
        );
      },
    );
  }

  Widget _buildTags() {
    if (post.tags.isEmpty) {
      return const SizedBox.shrink();
    }

    // 使用 Wrap 实现标签的流式布局
    return Wrap(
      spacing: 5.0, // 标签之间的水平间距
      runSpacing: 5.0, // 标签之间的垂直间距
      children: post.tags.map((tag) {
        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 2),
          decoration: BoxDecoration(
            color: const Color(0x33959595), // 标签的背景色（深色系中稍微亮一点的颜色）
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text(
            tag,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w400,
            ),
          ),
        );
      }).toList(),
    );
  }

  // --- 底部布局 ---
  Widget _buildFooter() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        //  观看图标和数量
        _buildAction('u_eye', post.watch),
        //  点赞图标和数量
        _buildAction('u_heart_sign', post.likes, isLiked: true),

        //  评论图标和数量
        _buildAction('u_comment_message', post.comments),

        // 分享图标和数量
        _buildAction('u_share', post.shares),
      ],
    ).paddingSymmetric(horizontal: 12);
  }

  // 底部动作按钮封装
  Widget _buildAction(String imgPath, int count, {bool isLiked = false}) {
    return Column(
      children: [
        Image.asset('assets/images/${imgPath}.png', width: 24, height: 24),

        Text(
          _formatCount(count),
          style: const TextStyle(
            color: Colors.white,
            fontSize: 11,
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  // 格式化数字 (例如 1200 -> 1.2k)
  String _formatCount(int count) {
    if (count >= 1000) {
      return '${(count / 1000).toStringAsFixed(1)}k';
    }
    return count.toString();
  }
}
